package org.rainbow.auctionplatform.service;

import org.quartz.SchedulerException;
import org.rainbow.auctionplatform.bean.Lot;
import org.rainbow.auctionplatform.dao.AddMapper;
import org.rainbow.auctionplatform.model.QuartzJobModel;
import org.rainbow.auctionplatform.properties.UploadFileProperties;
import org.rainbow.auctionplatform.utils.ImageCompress;
import org.rainbow.auctionplatform.utils.QuartzJobManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;

@Service
public class AddService {

    // 插入成功
    public final static int INSERT_SUCCESS = 0;
    // 插入失败的其他错误
    public final static int INSERT_ERROR = -1;
    // uid为空错误
    public final static int INSERT_UID_NULL = -100;

    // 更新成功
    public final static int UPDATE_SUCCESS = 0;
    // 更新失败的其他错误
    public final static int UPDATE_ERROR = -1;

    @Resource
    UploadFileProperties uploadFileProperties;

    private final AddMapper addMapper;

    private final QuartzJobManager quartzJobManager;

    @Autowired
    public AddService(AddMapper addMapper, QuartzJobManager quartzJobManager) {
        this.addMapper = addMapper;
        this.quartzJobManager = quartzJobManager;
    }

    /**
     * 插入拍品信息
     * @param lot 需要插入的拍品信息
     * @return 错误信息
     */
    public int insertLot(Lot lot) {
        // 插入成功标识
        boolean insert_flag;
        // 插入错误消息
        String error_msg = "";
        try {
            insert_flag = addMapper.insertLot(lot);
        } catch (Exception e) {
            e.printStackTrace();
            error_msg = e.getCause().getMessage();
            insert_flag = false;
        }
        if (insert_flag) {
            QuartzJobModel quartzJobModel = new QuartzJobModel();
            quartzJobModel.setJobName(lot.getLotId().toString());
            quartzJobModel.setTargetClassName("org.rainbow.auctionplatform.job.AuctionEndedJob");
            // 获得结束拍卖时间
            String endDate = lot.getEndDate();
            String[] s = endDate.split(" ");
            String[] date = s[0].split("-");
            String[] time = s[1].split(":");
            // 设置 cron表达式
            quartzJobModel.setCronExpression(time[2] + " " + time[1] + " " + time[0] + " " + date[2] + " " + date[1] + " ? " + date[0]);
            try {
                quartzJobManager.addJob(quartzJobModel, false);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
            return INSERT_SUCCESS;
        } else {
            resetMaxLFid();
            if (error_msg.contains("'uid' cannot be null")) {
                return INSERT_UID_NULL;
            }
            return INSERT_ERROR;
        }
    }

    /**
     * 上传图片
     * @param image 需要上传的图片
     * @param fileName 上传图片的名称
     * @return 错误信息
     */
    public int uploadImage(MultipartFile image, String fileName, Integer lot_id) {
        return ImageCompress.compressFile(image, lot_id + "-" + fileName, uploadFileProperties.getImagePath() + lot_id + File.separator);
    }

    /**
     * 上传图片后更新images字段
     * @param lot_id 更新的id
     * @param images 更新的images内容
     * @return 错误信息
     */
    public int updateImages(Integer lot_id, String images) {
        boolean b;
        try {
            b = addMapper.updateImages(lot_id, images);
        } catch (Exception e) {
            e.printStackTrace();
            b = false;
        }
        if (b) {
            return UPDATE_SUCCESS;
        } else {
            return UPDATE_ERROR;
        }
    }

    /**
     * 重置自增id缓存
     * mysql的自增会在插入失败事务回滚时继续自增，所以需要在回滚后先查出实际的最大LotId
     * 然后把缓存中的自增LFid重置为最大LotId+1
     */
    public void resetMaxLFid() {
        int maxId;
        try {
            maxId = addMapper.selectMaxLFid();
        } catch (Exception e) {
            maxId = 1000;
        }
        if (maxId != 0) {
            addMapper.resetMaxLFid(maxId + 1);
        }
    }
}
